//
//  SummaryViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/3.
//

#import "SummaryViewController.h"
#import "GradientArcProgressView.h"
#import "CourseSummaryManager.h"
#import "CourseSummaryModel.h"
#import "CourseGrammarViewController.h"
#import "WordCheckinView.h"
#import "CheckinShareManager.h"
#import "CheckinModel.h"
#import "TaskUpdateManager.h"
#import <WXApi.h>

@interface SummaryViewController ()<JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UIButton *coinBtn;
@property(nonatomic,strong)UILabel *percentLabel;
@property(nonatomic,strong)UILabel *countLabel;
@property(nonatomic,strong)GradientArcProgressView *percentProgressView;
@property(nonatomic,strong)GradientArcProgressView *countProgressView;
@property(nonatomic,strong)CourseSummaryManager *courseSummaryManager;
@property(nonatomic,strong)CourseSummaryModel *summaryModel;
@property(nonatomic,strong)WordCheckinView *checkinView;
@property(nonatomic,strong)CheckinShareManager *checkinShareManager;
@property(nonatomic,strong)CheckinModel *checkinModel;
@property(nonatomic,strong)TaskUpdateManager *taskUpdateManager;
@property(nonatomic,strong)UIImageView *topImageView;
@property(nonatomic,strong)UIButton *nextBtn;
@property(nonatomic,strong)UIButton *checkinBtn;

@end

@implementation SummaryViewController

-(CourseSummaryManager *)courseSummaryManager{
    if(!_courseSummaryManager){
        _courseSummaryManager = [[CourseSummaryManager alloc]init];
        _courseSummaryManager.delegate = self;
    }
    return _courseSummaryManager;
}

-(CheckinShareManager *)checkinShareManager{
    if(!_checkinShareManager){
        _checkinShareManager = [[CheckinShareManager alloc]init];
        _checkinShareManager.delegate = self;
    }
    return _checkinShareManager;
}

-(TaskUpdateManager *)taskUpdateManager{
    if(!_taskUpdateManager){
        _taskUpdateManager = [[TaskUpdateManager alloc]init];
        _taskUpdateManager.delegate = self;
    }
    return _taskUpdateManager;
}


-(void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
    [self loadData];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.isTotal == YES) {
        [self popGestureClose];
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (self.isTotal == YES) {
        [self popGestureOpen];
    }
}

- (void)defaultBackSet{
    [self.customNavigationBar setLeftItemWithIcon:[UIImage imageNamed:@"nav_back_logo"]];
    [self.customNavigationBar.leftButton addTarget:self action:@selector(__backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)__backButtonClicked:(UIButton*)btn{
    if (self.isTotal == YES) {
        //返回课程列表页面
        [self.navigationController popViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"SummaryClose" object:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = [UIColor whiteColor];
    
    CGFloat w550 = [DeviceUtils getAdaptedWidthForDesignWidth:550 andCurrentAvailableWidth:self.currentAvailableWidth];
    CGFloat w310 = [DeviceUtils getAdaptedWidthForDesignWidth:310 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(isIPAD){
        if(w310 > (self.currentAvailableHeight-100-11-112-38-11-96
                   )){
            w310 = self.currentAvailableHeight-100-11-112-38-11-96;
        }
        if(w550 > self.currentAvailableHeight){
            w550 = w310+210;
        }
    }
    UIImageView *topImageView = [[UIImageView alloc]init];
    topImageView.image = [UIImage imageNamed:@"summary_top_bg"];
    [self.view addSubview:topImageView];
    [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(@0);
        make.height.mas_equalTo(w550);
    }];
    self.topImageView = topImageView;
    
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.font = JPUIFontNotoSansJPMedium(35);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.numberOfLines = 0;
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(w310);
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
    }];
    
    __weak typeof(self)self_weak_ = self;
    CGFloat w48 = [DeviceUtils getAdaptedWidthForDesignWidth:48 andCurrentAvailableWidth:self.currentAvailableWidth];
    NSArray *arr = @[@"本课进度",@"本课已学"];
    for(NSInteger i = 0;i < 2;i++){
        UIView *bgView = [[UIView alloc]init];
        bgView.tag = 200+i;
        [self.view addSubview:bgView];
        [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(@112);
            if(isIPAD){
                make.top.mas_equalTo(self_weak_.titleLabel.mas_bottom).offset(11);
            }else{
                make.top.mas_equalTo(kWFit(399)+11);
            }
            if(i == 0){
                make.left.mas_equalTo(w48);
            }else{
                make.right.mas_equalTo(-w48);
            }
        }];
        UILabel *pTitleLabel = [[UILabel alloc]init];
        pTitleLabel.font = JPUIFontPingFangSCRegular(16);
        pTitleLabel.textColor = KFontGrayColor;
        pTitleLabel.textAlignment = NSTextAlignmentCenter;
        pTitleLabel.text = arr[i];
        [self.view addSubview:pTitleLabel];
        [pTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(bgView.mas_bottom).offset(16);
            make.height.mas_equalTo(@22);
            make.centerX.mas_equalTo(bgView);
        }];
        if(i == 0){
            self.percentProgressView = [[GradientArcProgressView alloc]initWithFrame:CGRectMake(0, 0, 112, 112) backgroundColor:UIColorHex(0xE8FAF5) startColor:UIColorHex(0xE8FAF5) endColor:KThemeColor];
            [bgView addSubview:self.percentProgressView];

            self.percentLabel = [[UILabel alloc]init];
            self.percentLabel.font = JPUIFontInterMedium(22);
            self.percentLabel.textAlignment = NSTextAlignmentCenter;
            self.percentLabel.textColor = KFontBlackColor;
            self.percentLabel.text = @"0%";
            [bgView addSubview:self.percentLabel];
            [self.percentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@27);
                make.left.mas_equalTo(@12);
                make.right.mas_equalTo(@-12);
                make.centerY.mas_equalTo(bgView);
            }];
        }else{
            
            self.countProgressView = [[GradientArcProgressView alloc]initWithFrame:CGRectMake(0, 0, 112, 112) backgroundColor:UIColorHex(0xFFF1E8) startColor:UIColorHex(0xFFF1E8) endColor:UIColorHex(0xFF781D)];
            [bgView addSubview:self.countProgressView];
            
            self.countLabel = [[UILabel alloc]init];
            self.countLabel.textAlignment = NSTextAlignmentCenter;
            self.countLabel.attributedText = [self changeCountStr:@"0" andStr2:@"0"];
            [bgView addSubview:self.countLabel];
            [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@27);
                make.left.mas_equalTo(@12);
                make.right.mas_equalTo(@-12);
                make.centerY.mas_equalTo(bgView);
            }];
        }
    }
    
    CGFloat b_w = (self_weak_.currentAvailableWidth-48)/2.0;
    UIButton *nextBtn = [[UIButton alloc]init];
    if(self.isTotal == YES){
        [nextBtn setTitle:@"本课语法" forState:UIControlStateNormal];
    }else{
        [nextBtn setTitle:@"继续下一组" forState:UIControlStateNormal];
    }
    nextBtn.backgroundColor = KThemeColor;
    nextBtn.layer.cornerRadius = 23;
    nextBtn.layer.masksToBounds = YES;
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nextBtn.titleLabel.font = JPUIFontPingFangSCMedium(16);
    [nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.width.mas_equalTo(b_w);
        make.height.mas_equalTo(@46);
        make.bottom.mas_equalTo(@-50);
    }];
    if(self.isTotal == YES&&(!self.courseModel.grammarFile||[self.courseModel.grammarFile isEqualToString:@""])){
        //没有本课语法
        nextBtn.hidden = YES;
    }
    self.nextBtn =  nextBtn;
    
    UIButton *checkinBtn = [[UIButton alloc]init];
    [checkinBtn setTitle:@"打卡" forState:UIControlStateNormal];
    checkinBtn.backgroundColor = [UIColor whiteColor];
    checkinBtn.layer.borderColor = UIColorHex(0xFF781D).CGColor;
    checkinBtn.layer.borderWidth = 2.0;
    checkinBtn.layer.cornerRadius = 23;
    checkinBtn.layer.masksToBounds = YES;
    [checkinBtn setTitleColor:UIColorHex(0xFF781D) forState:UIControlStateNormal];
    checkinBtn.titleLabel.font = JPUIFontPingFangSCMedium(16);
    checkinBtn.ym_acceptEventInterval = 2.0;
    [checkinBtn addTarget:self action:@selector(checkinBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:checkinBtn];
    [checkinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-16);
        if(self_weak_.isTotal == YES&&(!self_weak_.courseModel.grammarFile||[self_weak_.courseModel.grammarFile isEqualToString:@""])){
            make.width.mas_equalTo(self_weak_.currentAvailableWidth-32);
        }else{
            make.width.mas_equalTo(b_w);
        }
        make.height.mas_equalTo(@46);
        make.bottom.mas_equalTo(@-50);
    }];
    self.checkinBtn = checkinBtn;
    
    self.coinBtn = [[UIButton alloc]init];
    [self.coinBtn setImage:[UIImage imageNamed:@"summary_coin_logo"] forState:UIControlStateNormal];
    [self.coinBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.coinBtn.titleLabel.font = JPUIFontInterMedium(14);
    self.coinBtn.backgroundColor = UIColorHex(0xFF781D);
    self.coinBtn.layer.cornerRadius = 23/2.0;
    self.coinBtn.layer.masksToBounds = YES;
    [self.view addSubview:self.coinBtn];
    CGFloat c_w = [self getStringWidthWithText:self.coinBtn.titleLabel.text font:self.coinBtn.titleLabel.font viewHeight:23];
    [self.coinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-18);
        make.bottom.mas_equalTo(checkinBtn.mas_top).offset(11.5);
        make.height.mas_equalTo(@23);
        make.width.mas_equalTo(12+c_w+16);
    }];
    self.coinBtn.hidden = YES;
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    if (isIPAD) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            // 更新导航栏和背景视图的大小
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth, kYM_NAVIGATIONBAR_HEIGHT);
            CGFloat w550 = [DeviceUtils getAdaptedWidthForDesignWidth:550 andCurrentAvailableWidth:self.currentAvailableWidth];
            CGFloat w340 = [DeviceUtils getAdaptedWidthForDesignWidth:340 andCurrentAvailableWidth:self.currentAvailableWidth];
            if(isIPAD){
                if(w340 > (self.currentAvailableHeight-100-11-112-38-11-96
                           )){
                    w340 = self.currentAvailableHeight-100-11-112-38-11-96;
                }
            }
            if(w550 > self.currentAvailableHeight){
                w550 = w340+210;
            }
            [self.topImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(w550);
            }];
            [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(w340);
            }];
            __weak typeof(self)self_weak_ = self;
            CGFloat w48 = [DeviceUtils getAdaptedWidthForDesignWidth:48 andCurrentAvailableWidth:self.currentAvailableWidth];
            for(NSInteger i = 0;i < 2;i++){
                UIView *bgView = [self.view viewWithTag:200+i];
                [bgView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(self_weak_.titleLabel.mas_bottom).offset(11);
                    if(i == 0){
                        make.left.mas_equalTo(w48);
                    }else{
                        make.right.mas_equalTo(-w48);
                    }
                }];
            }
            CGFloat b_w = (self.currentAvailableWidth-48)/2.0;
            [self.nextBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(b_w);
            }];
            [self.checkinBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                if(self_weak_.isTotal == YES&&(!self_weak_.courseModel.grammarFile||[self_weak_.courseModel.grammarFile isEqualToString:@""])){
                    make.width.mas_equalTo(self_weak_.currentAvailableWidth-32);
                }else{
                    make.width.mas_equalTo(b_w);
                }
            }];
            
            if(self.checkinView){
                self.checkinView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
                self.checkinView.currentAvailableWidth = self.currentAvailableWidth;
                self.checkinView.currentAvailableHeight = self.currentAvailableHeight;
                [self.checkinView refreshWidth];
            }
            
        });
    }
}

-(NSMutableAttributedString*)changeCountStr:(NSString*)str andStr2:(NSString*)str2{
    NSMutableAttributedString *pStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@/%@词",str,str2]];
    [pStr addAttribute:NSFontAttributeName value:JPUIFontInterMedium(22) range:NSMakeRange(0,str.length)];
    [pStr addAttribute:NSFontAttributeName value:JPUIFontInterRegular(14) range:NSMakeRange(str.length,pStr.length-str.length)];
    [pStr addAttribute:NSForegroundColorAttributeName value:KFontBlackColor range:NSMakeRange(0,str.length)];
    [pStr addAttribute:NSForegroundColorAttributeName value:KFontGrayColor range:NSMakeRange(str.length,pStr.length-str.length)];
    return pStr;
}

#pragma mark - 刷新界面
-(void)refreshUI{
    self.coinBtn.hidden = NO;
    self.titleLabel.text = self.summaryModel.support;
    self.percentLabel.text = [NSString stringWithFormat:@"%@%%",self.summaryModel.percent];
    self.countLabel.attributedText = [self changeCountStr:self.summaryModel.finish andStr2:self.summaryModel.sum];
    self.percentProgressView.progress = self.summaryModel.percent.floatValue/100;
    self.countProgressView.progress = self.summaryModel.finish.floatValue/self.summaryModel.sum.floatValue;
    [self.coinBtn setTitle:[NSString stringWithFormat:@" +%@",self.summaryModel.score] forState:UIControlStateNormal];
    CGFloat c_w = [self getStringWidthWithText:self.coinBtn.titleLabel.text font:self.coinBtn.titleLabel.font viewHeight:23];
    [self.coinBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(12+c_w+16);
    }];
}

#pragma mark - 获取课程小结数据
-(void)loadData{
    self.courseSummaryManager.ucId = self.courseModel.ucId;
    self.courseSummaryManager.wordIds = self.wordIds;
    [self.courseSummaryManager loadData];
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.courseSummaryManager]){
        NSDictionary *dic = manager.response.content;
        self.summaryModel = [CourseSummaryModel mj_objectWithKeyValues:dic[@"data"]];
        [self refreshUI];
    }
    
    if([manager isEqual:self.checkinShareManager]){
        NSDictionary *dic = manager.response.content;
        self.checkinModel = [CheckinModel mj_objectWithKeyValues:dic[@"data"]];
        [self showCheckinView];
    }
    
    if([manager isEqual:self.taskUpdateManager]){
        [JPProgressHUD showMsg:@"分享成功"];
    }
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}

#pragma mark - 下一组或者语法
-(void)nextBtnClick{
    if(self.isTotal == YES){
        CourseGrammarViewController *vc = [[CourseGrammarViewController alloc]init];
        vc.file = self.courseModel.grammarFile;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
        if(_readBlock){
            _readBlock();
        }
    }
}

#pragma mark - 打卡
-(void)checkinBtnClick{
    self.checkinShareManager.dictId = @"18";
    [self.checkinShareManager loadData];
}

-(void)showCheckinView{
    if(!self.checkinView){
        self.checkinView = [[WordCheckinView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,self.currentAvailableHeight)];
    }
    self.checkinView.currentAvailableWidth = self.currentAvailableWidth;
    self.checkinView.currentAvailableHeight = self.currentAvailableHeight;
    self.checkinView.checkinModel = self.checkinModel;
    if(KEY_WINDOW){
        [KEY_WINDOW addSubview:self.checkinView];
        __weak typeof(self)self_weak_ = self;
        [self.checkinView setShareBlock:^(NSInteger index, UIImage * _Nonnull shareImage) {
            [self_weak_.checkinView removeFromSuperview];
            [self_weak_ shareImageToWeChatAndIndex:index andImage:shareImage];
        }];
    }
}

#pragma mark - 微信 微信朋友圈分享
- (void)shareImageToWeChatAndIndex:(NSInteger)index andImage:(UIImage*)shareImage{
    // 创建微信消息对象
    WXMediaMessage *message = [WXMediaMessage message];
    // 设置缩略图
    if (shareImage) {
        [message setThumbImage:shareImage];
    }
    // 创建图片对象
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = UIImagePNGRepresentation(shareImage);
    message.mediaObject = imageObject;
    // 创建发送请求对象
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    if (index == 1){
        // 朋友圈
        req.scene = WXSceneTimeline;
    }else{
        // 会话
        req.scene = WXSceneSession;
    }
    // 发送请求
    __weak typeof(self)self_weak_ = self;
    [WXApi sendReq:req completion:^(BOOL success) {
        if (success) {
            [self_weak_ finfishTask];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [JPProgressHUD showMsg:@"分享失败"];
            });
        }
    }];
    
}


#pragma mark - 完成任务
-(void)finfishTask{
    //背词分享任务完成
    self.taskUpdateManager.dictId = @"19";
    [self.taskUpdateManager loadData];
}


@end
